package com.ctgu.computer.schedule;

import com.ctgu.computer.domain.po.CommentTextSenderInfo;
import com.ctgu.computer.domain.po.TextInfo;
import com.ctgu.computer.mapper.CommentMapper;
import com.ctgu.computer.mapper.TopicMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Slf4j
@RequiredArgsConstructor
public class ScheduleTask {

    private final CommentMapper commentMapper;
    private final TopicMapper topicMapper;
    private final FileStorageService fileStorageService;
    // 已经被删除的帖子Id
    public static List<Integer> taskIds = new ArrayList<>();
    public static List<String> imagePaths = new ArrayList<>();

    public static Map<Integer,Integer> textIdReadCount = new HashMap<>();

    // 每天凌晨3点自动清理数据库无用字段
    @Scheduled(cron = "0 0 3 * * ? ")
    public void deleteCommentTask(){
        if(!taskIds.isEmpty()){
            List<CommentTextSenderInfo> commentTextSenderInfos =
                    topicMapper.batchSelectSenderToTextByToCommentTextId(taskIds);
            // 被删帖相关的评论id
            List<Integer> commentIds = commentTextSenderInfos.stream()
                    .map(CommentTextSenderInfo::getCommentId)
                    .collect(Collectors.toList());
            commentMapper.batchDelete(commentIds);
            taskIds.clear();
        }
        log.info("定时清理评论完毕...");
        if(!imagePaths.isEmpty()){
            for (String imagePath : imagePaths) {
                fileStorageService.delete(imagePath);
            }
        }
        imagePaths.clear();
        log.info("定时清理图片完成...");
        commentMapper.batchDeleteGood();
        topicMapper.batchDeleteGood();
        log.info("定时清理点赞情况完成...");
    }

    @Scheduled(cron = "0/5 * * * * ? ")
    public void updateTask(){
        if(!textIdReadCount.isEmpty()){
            textIdReadCount.forEach((textId, readCount)->{
                topicMapper.update(TextInfo.builder()
                                .textId(textId)
                                .readCount(readCount)
                        .build());
            });
            textIdReadCount.clear();
            log.info("延迟更新阅读数量成功...");
        }
    }

}
